<!DOCTYPE html>
<html lang="zh-cn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0,maximum-scale=1.0, user-scalable=no">
    <title>User1</title>
</head>
<body>
<p style="width: 100%;height: 44px;background-color: #eee;position: fixed;top:0;left: 0;margin: 0;text-align:center;line-height:44px;">RACMsg聊天室</p>
<div style="width: 100%;height: 50px;background-color: #eee;position: fixed;bottom:0;left: 0;margin: 0;">
    <textarea id="text" style="resize: none;width:70%;height:30px;margin: 8px 2%;float:left;border-radius: 3px;border: 1px #ddd"></textarea>
    <button onclick="goSend()" style="width: 20%;float: right;height:35px;margin: 8px 2% 8px 0;background-color: dodgerblue;color: white;border-radius: 3px;border: 1px dodgerblue">发送消息</button>
</div>

<div id="msgDiv" style="width: 100%;margin-top:44px;overflow: hidden;padding: 10px;">

</div>

</body>

<script>
    var pathSp = window.location.href.split('=');
    var username = pathSp[pathSp.length-1];
    var url = "ws://localhost:8080/websocket/"+username;
    var socket = new WebSocket(url);

    function goSend() {
        socket.send(document.getElementById("text").value);
    }

    //连接发生错误的回调方法
    socket.onerror = function(event) {
        console.log("WebSocket连接发生错误");
    };

    //连接成功建立的回调方法
    socket.onopen = function(event) {
        console.log("WebSocket连接成功");
    };

    //接收到消息的回调方法
    socket.onmessage = function(event) {
        var div = document.getElementById("msgDiv");
        var html = document.createElement("p");
        var returnData = JSON.parse(event.data);
        console.log(event.data);
        html.innerHTML = returnData.user+"："+returnData.msg;
        div.appendChild(html);
    };

    //连接关闭的回调方法
    socket.onclose = function() {
        console.log("WebSocket连接关闭");
    };

    //监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
    window.onbeforeunload = function() {
        closeWebSocket();
    };

    //关闭WebSocket连接
    function closeWebSocket() {
        socket.close();
    }


</script>

</html>